import { store } from '@/store';
import { defineStore } from 'pinia';
import { resetRouter } from "@/router";
import { useStorage } from "@vueuse/core"
import { TOKEN_KEY } from "@/enums/CacheEnum"

//api
import { userLogin, registerUser, getUserInfoFn } from '@/api/user'


interface UserInfo {
  username?: string;
  nickname?: string;
  avatar?: string;
  roles: string[];
  userAuthList: string[];
}
export const useUserStore = defineStore('user', () => {
  const user = ref<UserInfo>({
    roles: [],
    userAuthList: [],
  });

  // 注册用户
  async function register(userForm: object) {
    try {
      let res = await registerUser(userForm);
      return res;
    } catch (error) {
      console.log(error, 'register')
    }
  }

  //登录用户
  function login(userForm: object) {
    return new Promise<any>((resolve, reject) => {
      userLogin(userForm).then((response) => {
        const { access_token, refresh_token } = response.data;
        localStorage.setItem(TOKEN_KEY, `Bearer ${access_token}`) // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
        resolve(response.data);
      }).catch((error) => {
        reject(error);
      });
    })
  }

  // 获取用户信息
  async function getUserInfo(): Promise<Record<string, any>> {
    try {
      let res = await getUserInfoFn();
      const { data } = res;
      user.value = { roles: data.userInfo.role, userAuthList: data.userAuthList, };
      return data;
    } catch (error) {
      console.log(error, 'getUserInfo')
      throw error;
    }
  }



  // remove token
  function resetToken() {
    return new Promise<void>((resolve) => {
      localStorage.setItem(TOKEN_KEY, "");
      resetRouter();
      resolve();
    });
  }
  return { user, register, login, getUserInfo, resetToken }
})

export function useUserStoreHook() {
  return useUserStore(store);
}